import 'package:flutter/material.dart';

class LazyIndexStack extends StatefulWidget {
  final LazyIndexStackController controller;
  const LazyIndexStack({super.key, required this.controller});

  @override
  State<LazyIndexStack> createState() => _LazyIndexStackState();
}

class _LazyIndexStackState extends State<LazyIndexStack> {
  @override
  void initState() {
    super.initState();
    widget.controller._bind(this);
    widget.controller._init();
  }

  @override
  void dispose() {
    widget.controller._dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => widget.controller._build();

  void _rebuild() => setState(() {});
}

class LazyIndexStackController {
  final List<Widget> _children; // 外部传入的视图列表
  final List<Widget> _items; // 主要存储要展示的组件列表
  int _index = 0;
  _LazyIndexStackState? _state;

  LazyIndexStackController({required List<Widget> children, int index = 0})
      : _index = index,
        _children = children,
        _items = List.generate(children.length, (index) => const SizedBox.shrink());

  void changeIndex(int index) {
    assert(index >= 0 && index < _children.length);
    _replaceView(_index = index);
    _state?._rebuild();
  }

  void _replaceView(int index) {
    if (_items[index] is SizedBox) {
      _items[index] = _children[index];
    }
  }

  void _init() => _replaceView(_index);

  void _bind(_LazyIndexStackState state) => _state = state;

  void _dispose() {
    _items.clear();
    _children.clear();
  }

  Widget _build() => IndexedStack(index: _index, children: _items);
}